<?php

namespace App\Http\Controllers;

use App\Datas\Pay;
use App\Datas\System;
use App\Datas\User;
use App\Datas\UserGoogleSubscribe;
use App\Datas\UserDrawing;
use App\Datas\UserOntrial;
use App\Tools\FunTool;
use App\Tools\GooglePay;
use App\Tools\Oppo;
use App\Tools\RegionPrice;
use App\Tools\WechatPay;
use App\Tools\Af;
use App\Tools\Tester;
use App\Tools\IPFactory;
use App\Datas\EventList;
use fengkui\Pay\Wechat;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Validation\Validator;
use Ixudra\Curl\Facades\Curl;
use LeeHom\AppleInAppPurchaseVerification;
use sn01615\iap\google\Verify;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use WeChatPay\Util\PemUtil;
use Yurun\PaySDK\Alipay\Params\PublicParams;
use Yurun\PaySDK\Weixin\SDK;


class PayController extends Controller
{

    protected $dataUser;
    protected $dataPay;
    protected $dataUserOntrial;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->dataUser = new User();
        $this->dataPay = new Pay();
        $this->dataUserOntrial = new UserOntrial();
    }


    private $quantity = 1;

    private $appleSubscribe = false;

    private $appleSunscribeProduct = "";

    public function getPayList() {
        $userId = $this->getTokenUser();
        $version = $this->getVersion();
        $channel = $this->getChannel();
        $platform = $this->getPlatform();

        $vip = [0];
        if ($userId) {
            $userData = $this->dataUser->getUser($userId);
            if ($userData['vip_surplus'] > 0 || $userData['vip_surplus'] == -1) {
                $vip[] = 1;
            }
        }

        if ($platform == 1 && $version == "1.4.1") {
            $data = $this->dataPay->getNewVersionData();
        } else {
            $data = $this->dataPay->getRuleList(0, $channel, $vip, $version);
        }

        $userPayCount = 0;
        if ($userId) {
            $userPayCount = $this->dataPay->getUserCountNoDot($userId);
        }

        foreach ($data as $key => $item) {

            //增加参数判断当前的数据是否是打八折的数据
            $data[$key]['price'] = ceil($data[$key]['price'] / 100);
            $data[$key]['original_price'] = ceil($data[$key]['original_price'] / 100);
            $data[$key]['is_free_sub'] = false;
            //新版本并且不是ios
            if (version_compare($version,  "1.5.0") < 0 && $platform != 1) {
                //增加参数判断当前的数据是否是打八折的数据
                $data[$key]['is_discount'] = $userPayCount == 1 ? true : false;
                if ($userPayCount == 1) {
                    $data[$key]['price'] = ceil($data[$key]['price'] * 0.8);
                    $data[$key]['google_order_id'] = $data[$key]['google_discount_order_id'];
                }
            }
        }
        $data = array_values($data);
        return $this->buildReturn(Code::SUCCESS, $data);
    }

    /**
     * 获取年会员/终生会员折扣
     */
    public function getRuleDiscountList(){

        $data = $this->dataPay->getRuleDiscount();

        return $this->buildReturn(Code::SUCCESS, $data);
    }


    /**
     * 折扣购买列表
     * @return array
     */
    public function getDiscountPayList(Request $request) {
        $type = $request->get('type') ?? 1;
        $version = $this->getVersion();
        $data = $this->dataPay->getRuleList($type, 'default', [0], $version);
        foreach ($data as $key => $item) {
            $data[$key]['price'] = sprintf("%.2f", floatval($item['price'])/100);
            $data[$key]['original_price'] = sprintf("%.2f", floatval($item['original_price'])/100);
        }
        return $this->buildReturn(Code::SUCCESS, $data);
    }

    /**
     * 获取点数
     * @return array
     */
    public function getDotRules(Request $request)
    {
        $type = $request->get('type') ?? 1;
        if ($type == 1) {
            //1000点
            $id = 157;
        } else if ($type == 2) {
            //3000点
            $id = 158;
        }
        $data = $this->dataPay->getDotRules($id);
        return $this->buildReturn(Code::SUCCESS, $data);
    }

    public function createOrder(Request $request) {
        $this->validate($request, [
            'rule_id' => ['required'],
            'pay_type' => ['required'],
        ]);
        //$ruleId = 1;
        //$payType = 1;

        $ruleId = $request->get('rule_id');
        $payType = $request->get('pay_type');
        $version = $this->getVersion();
        $platform = $this->getPlatform();
        $deviceId = $this->getDeviceId();
        $deviceId = !empty($deviceId) ? $deviceId : "";
        $ruleData = $this->dataPay->getRule($ruleId);
        //是否支持未登录付费
        $checkNologinPay = $this->checkNoLoginPay();

        if (!$ruleData) {
            return $this->buildReturn(Code::PARAM_ERROR);
        }

        $userId = $this->getTokenUser();

        if (!$checkNologinPay) {
            if (!$userId) {
                return $this->buildReturn(Code::NOT_LOGIN);
            }
            $userPayCount = $this->dataPay->getUserCount($userId);
        } else {
            //支撑无登录下单，也要兼容登录下单
            if (!$userId) {
                $userId = 0;
                $userPayCount = $this->dataPay->getDeviceIdCount($deviceId,$platform);
            } else {
                $userPayCount = $this->dataPay->getUserCount($userId);
            }
        }

        if ($userId > 0) {
            $userInfo = $this->dataUser->getUser($userId);
            if ($userInfo["is_super_vip"] == 1 && $ruleId == env("LEFTTIME_RULEID")) {
                return $this->buildReturn(Code::REPEAT_BUY_SUPER_VIP_ERROR);
            }
        }

        $accountName = '';
        
        $googleId = $ruleData['google_order_id'];
        //判断用户是否是第二次支付，是第二次支付，order表存入打八折的google商品id
        //$userPayCount = $this->dataPay->getUserCount($userId);
        if (version_compare($version,  "1.5.0") < 0 && $platform != 1) {
            $googleId = $userPayCount == 1 ? $ruleData['google_discount_order_id'] : $ruleData['google_order_id'];
        }


        if (version_compare($version,  env('NEW_VERSION')) >= 0 && $platform != 1 && $userPayCount == 1) {
            //$ruleData['price'] = ceil($ruleData['price'] / 100 * 0.8 * 100);
        }

        $orderId = $this->dataPay->insertOrder($ruleId, $ruleData['price'], $ruleData['type'], $ruleData['len'], $ruleData['dot'], $payType, $userId, $deviceId,$accountName, $ruleData['ecy_len'], $ruleData['google_is_subscribe'], $ruleData['drawing_id'], $ruleData['recommend'], $googleId, $version, $platform);

        $data = ['order_id' => $orderId];

        if($payType == 1) {
            $config = config('pay.'.$accountName);
            $pkg = $this->getPkg();
            if ($pkg == 'com.xdx.dreamcatcher') {
                $key = 'weixin_appid_com.xdx.dreamcatcher';
                $appid = config('pay')[$key];
                //Log::info($appid);
                $config['appid'] = $appid;
            }
            $order = [
                'out_trade_no' => $orderId,
                'total_fee' => $ruleData['price'],
                //'total_fee' => 1,
                'body' => '充值'
            ];
            $result = \Yansongda\Pay\Pay::wechat($config)->app($order);
            $data['wxpay'] = json_decode($result->getContent(), true);
        }

        if($payType == 5) {
            $userInfo = $this->dataUser->getUser($userId);
            $config = config('pay.'.$accountName);
            $order = [
                'out_trade_no' => $orderId,
                'total_fee' => $ruleData['price'],
                'openid' => $userInfo['jsweixin'],
                //'total_fee' => 1,
                'body' => '充值'
            ];
            $result = \Yansongda\Pay\Pay::wechat($config)->miniapp($order);
            $data['wxpay'] = $result->toArray();
        }

        if($payType == 4) {
            $config = config('pay.alipay');
            $order = [
                'out_trade_no' => $orderId,
                'total_amount' => $ruleData['price']/100,
                //'total_amount' => 0.01,
                'subject' => '充值'
            ];
            $result =  \Yansongda\Pay\Pay::alipay($config)->app($order);
            $data['alipay'] = $result->getContent();

        }
        $this->inOrderPash($deviceId);
        return $this->buildReturn(Code::SUCCESS, $data);
    }


    public function inOrderPash($deviceId) {
        try {
            $dataSystem = new System();
            $deviceInfo = $dataSystem->getDevice($deviceId);
            $cburl = $deviceInfo['ad_cburl'] ?? null;
            $source = $deviceInfo['ad_source'] ?? null;
            $channelId = $deviceInfo['channel_id'] ?? null;
            if (empty($cburl)) {
                return;
            }
            if (!in_array($channelId, ['toutiao-lz79','toutiao-zy79'])) {
                return;
            }
            if ($source != 'toutiao') {
                return;
            }
            if (time() - strtotime($deviceInfo['created_at']) < 90) {
                return;
            }
            if ($this->dataPay->hasModelBlock($deviceInfo['model'])) {
                return;
            }
            if ($this->dataPay->incInOrder($deviceId) > 1) {
                return;
            }
            $retData = Curl::to($cburl . '&event_type=2')->get();
            //Log::info('game_addiction', [ 'ret' => $retData]);
        } catch (\Exception $e) {
            Log::info('game_addiction', ['error']);
        }
    }


    /**
     * 支付宝回调
     */
    public function alipayNotify() {
        $aliconfig = config('pay.alipay');
        $alipay = \Yansongda\Pay\Pay::alipay($aliconfig);
        $data = $alipay->verify();
        $result = $data->toArray();
        if ($result) {
            echo "success";
            if ($result['trade_status'] == 'TRADE_SUCCESS') {
                $this->doPay($result['out_trade_no'], $result['trade_no']);
            }
        }
        return "success";
    }


    /**
     * 微信支付回调
     */
    public function weixinNotify($accountName) {
        $wxconfig = config('pay.'.$accountName);
        $wxPay = \Yansongda\Pay\Pay::wechat($wxconfig);
        $result = $wxPay->verify();
        $result = $result->toArray();

        //Log::info('weixinNotify', $result);

        if ($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            $orderId = $result['out_trade_no'];
            $externalOrderId = $result['transaction_id'];
            $this->doPay($orderId, $externalOrderId);
        }
        return '<xml>
            <return_code><![CDATA[SUCCESS]]></return_code>
            <return_msg><![CDATA[OK]]></return_msg>
            </xml>';
    }

    public function appleNotify(Request $request) {
        $this->validate($request, [
            'receipt' => ['required'],
            'order_id' => ['required'],
        ]);

        $receipt = $request->post('receipt');
        $orderId = $request->post('order_id');
        
		$oTester = new Tester();
		$bSandbox = $oTester->isTester($this->getDeviceId());

		//@todo >= 1.8.0 直接走沙盒
		$sVersion = $this->getVersion();
		//if(version_compare($sVersion, '1.8.0') >= 0) {
		//	$bSandbox = true;
		//}
        $orderInfo = DB::table('pay_order')->where('order_id',$orderId)->first();
        if (!empty($orderInfo)) {
            DB::table('pay_order')->where('id',$orderInfo->id)->update(['extend'=>json_encode(['order_id'=>$orderId,'receipt'=>$receipt]),'client_notify'=>1]);
        }
		$appleIAP = new AppleInAppPurchaseVerification($receipt, '46c5cf1c64084e5c81f3fe9d17a4be17', $bSandbox);
        $result = $appleIAP->validateReceipt();
        $result = json_decode($result, true);
        Log::info("appleNotify",["appleNotify" => $result, 'order_id' => $orderId]);
        //$orderData = $result['receipt']['in_app'][0] ?? null;
        $orderData = $result['latest_receipt_info'][0] ?? null;
        if (!$orderData) {
            return $this->buildReturn(Code::SUCCESS);
        }
        if ($result['receipt']['bundle_id'] != 'FA.FaceAppAI' ) {
            return $this->buildReturn(Code::SUCCESS);
        }
        $externalOrderId = $orderData['transaction_id'];
        $externalOrder = $this->dataPay->getOrderWithExternalOrderId($externalOrderId);
        if ($externalOrder) {
            return $this->buildReturn(Code::SUCCESS);
        }
        $this->doPay($orderId, $externalOrderId);
        return $this->buildReturn(Code::SUCCESS);
    }


    public function googleNotify(Request $request) {
        $this->validate($request, [
            'receipt' => ['required'],
            'order_id' => ['required'],
            'signature' => ['required'],
        ]);

        $receipt = $request->post('receipt');;
        $orderId = $request->post('order_id');
        $signature = $request->post('signature');

        $receipt = json_decode($receipt, true);
        Log::info("googleNotify", ['order_id'=>$orderId, '谷歌通知数据：' => $receipt]);
        $token = $receipt['purchaseToken'];
        $productId = $receipt['productId'];
        $quantity = $receipt["quantity"];

        // 订单号码用 google receipt 中的订单号
        $Result = GooglePay::payV3($orderId, $productId, $token);
        Log::info("googleNotify_result", ['order_id'=>$orderId, 'result' => $Result]);
        if (!$Result) {
            return $this->buildReturn(Code::ERROR);
        }
		$sOrderIDOfReceipt = $Result['order_id'];// Google Receipt 中的订单号码

        $externalOrderId = $receipt['orderId'];
        $externalOrder = $this->dataPay->getOrderWithExternalOrderId($externalOrderId);
        if ($externalOrder) {
            return $this->buildReturn(Code::ERROR);
        }
        $this->quantity = $quantity;
        $Res = $this->doPay($sOrderIDOfReceipt, $externalOrderId);
        
        return $this->buildReturn(Code::SUCCESS);
    }


    private function doPay($orderId, $externalOrderId,$transaction_order_id = "") {
        $orderInfo = $this->dataPay->getOrder($orderId);
        if ($orderInfo['status'] != 0) {
            return false;
        }
		$isSuperVip = false;

        DB::beginTransaction();
        try {

            $id = $orderInfo['id'];
            if ($this->quantity > 1) {
                $orderInfo["price"] = $orderInfo["price"] * $this->quantity;
                $orderInfo["dot"] = $orderInfo["dot"] * $this->quantity;
                $this->dataPay->updatePayById($id,[
                    "price" => $orderInfo["price"],
                    "dot" => $orderInfo["dot"]
                ]);
            }
            $this->dataPay->updatePay($id, $externalOrderId,$transaction_order_id);

            $userDrawing = new UserDrawing();
            
            //兼容无登录付费
            if($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                $this->dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
            }

            // if (version_compare($orderInfo['version'],  env('NEW_VERSION')) >= 0) {
            //     //兼容无登录付费
            //     if($orderInfo['len'] > 0 && $orderInfo['len'] != 36500 && $orderInfo["user_id"] > 0) {
            //         if ($orderInfo['is_gold'] == 1) {
            //             //续费黄金会员的时间
            //             $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
            //         } else {
            //             //续费普通画板的时间
            //             $userDrawing->updateUserDrawExp($orderInfo['user_id'], $orderInfo['drawing_id'], $orderInfo['len'] * 24 * 3600);
            //         }
            //     }
            // } else {
                if($orderInfo['len'] > 0) {
                    $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len']*24*3600, 'vip_exp');
                }

                if($orderInfo['ecy_len'] > 0) {
                    $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['ecy_len']*24*3600, 'rcy_vip_exp');
                }
            //}

            // 更新终生会员
            $isSuperVip = in_array($orderInfo["google_id"], config('app.pay_lifetime')) ? true : false;// 是否是终生会员
            if ($isSuperVip && $orderInfo["user_id"] > 0) {
                $this->dataUser->updateById($orderInfo['user_id'],["is_super_vip" => 1]);
            }

            //兼容无登录付费
            if ($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                //设置充值赠送点数动画值
                $this->dataUser->setDhNum($orderInfo['user_id'], $orderInfo['dot']);
            }

            DB::commit();
        } catch (\Exception $e) {
            Log::error("doPay_error",["error" => $e->getMessage(),"line" => $e->getLine()]);
            DB::rollBack();
            return false;
        }
        $guid = $orderInfo['device_id'];
        if (empty($guid)) {
            return null;
        }
        $systemData = new System();
        $deviceInfo = $systemData->getDevice($guid);

        /*上报订阅数据到AF 开始*/
        //$appid = $orderInfo['platform'] == 1 ? "" : "com.jxfq.dalle";
        $appid = FunTool::getAfAppidByPf($orderInfo['platform']);
        $af = new Af();
        if ($this->appleSubscribe) {
            $_aExt = ['line'=>__LINE__, 'in' => 'doPay', 'order' => $orderInfo, 'appleSubscribe' => $this->appleSubscribe];
            $af->subscribeEvent($deviceInfo['appsfly_id'],$appid,$_aExt);
            EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");

            $_aExt = ['line'=>__LINE__, 'in' => 'doPay', 'order' => $orderInfo, 'externalOrderId' => $externalOrderId];
            $af->payEvent($deviceInfo['appsfly_id'],$appid,$orderInfo['price'], $_aExt);
        } else {
            $_aExt = ['line'=>__LINE__, 'in' => 'doPay', 'order' => $orderInfo, 'externalOrderId' => $externalOrderId];
            $af->payEvent($deviceInfo['appsfly_id'],$appid,$orderInfo['price'], $_aExt);

			//@todo eks 购买终身会员事件上报
			if(true === $isSuperVip){
				EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");
			}
        }
        /*上报订阅数据到AF 结束*/

        $cbUrl = $deviceInfo['ad_cburl'] ?? '';
        $adSource = $deviceInfo['ad_source'] ?? '';
        $platform = $deviceInfo['platform'] ?? '';
        $channelId = $deviceInfo['channel_id'] ?? '';
        // 头条充值回调
        if (!empty($cbUrl) && $adSource == 'toutiao' && !in_array($channelId, ['toutiao-lz79','toutiao-zy79'])) {
            $props = ['pay_amount' => $orderInfo['price']];
            $props = strtolower(urlencode(json_encode($props)));
            //Curl::to($cbUrl . '&event_type=2'.'&props='.$props)->get();
            Curl::to($cbUrl . '&event_type=2')->get();

        }
        // 快手充值回调
        if (!empty($cbUrl) && $adSource == 'kuaishou') {
            $count = $this->dataPay->getUserCount($orderInfo['user_id']);
            $userData = $this->dataUser->getUser($orderInfo['user_id']);
            $regDateTime = strtotime($userData['created_at']);
            $todayTime=strtotime("today");
            if ($count == 1 && $regDateTime > $todayTime) {
                //Curl::to($cbUrl . '&event_type=3&event_time='.time() . '000' .'&purchase_amount=' .round($orderInfo['price']/100,2))->get();
                Curl::to($cbUrl . '&event_type=3&event_time=' . time() . '000')->get();
            }
        }
        // 网易充值回调
        if (!empty($cbUrl) && $adSource == 'wangyi') {
            $convAction = $platform=='ios' ? 'ios_purchase' : 'android_purchase';
            $res = Curl::to('http://conv.youdao.com/api/track?conv_ext='.$cbUrl.'&conv_action='.$convAction.'&order_amount='.$orderInfo['price'])->get();
            //writeLog('ad', "广告|网易|充值|结果", [$deviceInfo, $res]);
        }
        // B站充值回调
        if (!empty($cbUrl) && $adSource == 'bilibili') {
            $count = $this->dataPay->getUserCount($orderInfo['user_id']);
            $userData = $this->dataUser->getUser($orderInfo['user_id']);
            $regDateTime = strtotime($userData['created_at']);
            $todayTime=strtotime("today");
            if ($count == 1 && $regDateTime > $todayTime) {
                //$res = Curl::to($cbUrl . '&conv_type=USER_COST&conv_value='.$orderInfo['price'].'&conv_time='.time() . '000')->get();
                $res = Curl::to($cbUrl . '&conv_type=USER_COST&conv_time='.time() . '000')->get();
                //writeLog('ad', "广告|B站|充值|结果", [$deviceInfo, $res]);
            }
        }
        
        if ($channelId == 'oppo-01') {
            $count = $this->dataPay->getUserCount($orderInfo['user_id']);
            $userData = $this->dataUser->getUser($orderInfo['user_id']);
            $regDateTime = strtotime($userData['created_at']);
            $todayTime=strtotime("today");
            if ($count == 1 && $regDateTime > $todayTime) {
                $oppoTools = new Oppo();
                $oppoTools->sendData($deviceInfo['imei'], $deviceInfo['oaid'],'','',7,'', 1, $cbUrl);
            }
        }
        if (!empty($cbUrl) && $adSource == 'jsbilibili') {
            $count = $this->dataPay->getUserCount($orderInfo['user_id']);
            $userData = $this->dataUser->getUser($orderInfo['user_id']);
            $regDateTime = strtotime($userData['created_at']);
            $todayTime=strtotime("today");
            if ($count == 1 && $regDateTime > $todayTime) {
                $url = 'https://cm.bilibili.com/conv/api/conversion/ad/cb/v1?conv_type=USER_COST&conv_time='.time() . '000' . '&track_id=' . $cbUrl;
                $res = Curl::to($url)->get();
                //Log::info('jsbilibili-pay', [ 'ret' => $res ]);
            }
        }

        if (!empty($cbUrl) && $adSource == 'jstoutiao') {
            $count = $this->dataPay->getUserCount($orderInfo['user_id']);
            $userData = $this->dataUser->getUser($orderInfo['user_id']);
            $regDateTime = strtotime($userData['created_at']);
            $todayTime=strtotime("today");
            if ($count == 1 && $regDateTime > $todayTime) {
                $url = 'https://analytics.oceanengine.com/api/v2/conversion';
                $data = [
                    'event_type' => 'active_pay',
                    'context' => [
                        'ad' => [
                            'callback' => $cbUrl,
                        ]
                    ],
                    'timestamp' => time() * 1000
                ];
                $retData = Curl::to($url)->withData($data)->asJsonRequest()->asJsonResponse()->post();
                Log::info('jstoutiao-pay', [ 'ret' => $retData, 'req' => $data ]);
            }
        }

        return true;
    }


    /**
     * 谷歌商品购买通知
     */
    public function googleNotifyNew()
    {
        $json = file_get_contents('php://input');

        if (!is_string($json)) {
            return $this->buildReturn(Code::ERROR);
        }

        $notifyData = json_decode($json, true);
        if (!$notifyData || !is_array($notifyData)) {
            return $this->buildReturn(Code::ERROR);
        }

        if (!isset($notifyData['message']['data'])) {
            return $this->buildReturn(Code::ERROR);
        }

        Log::info("google_pay", ['data' => $notifyData]);
        $jsonData = base64_decode($notifyData['message']['data']);
        $data = json_decode($jsonData, true);
        Log::info("google_pay_data",["data" => $data]);
        //订阅购买
        if (isset($data['subscriptionNotification'])) {
            $subNotifi = $data['subscriptionNotification'];

            $result = GooglePay::payV4($data['packageName'], $subNotifi['subscriptionId'], $subNotifi['purchaseToken']);
            Log::info("google_pay_result", ['result' => $result]);
            $orderId = $result->externalAccountIdentifiers['obfuscatedExternalProfileId'];
            $notificationType = $subNotifi['notificationType'];
            $lastOrderId = $result->latestOrderId;
            $regionCode = $result->regionCode;

            if ( in_array($notificationType, [3,12,13,8])) {//3取消订阅,12撤销订阅,13已过期,8价格变动 
                $refundRes = $this->dataPay->googlePayRefund($orderId, $data, $notificationType);
                return $this->buildReturn(Code::SUCCESS);
            }

            //4:新订阅  2:续订  1:从帐号保留状态恢复了订阅(扣款成功)
            if ($notificationType != 4 && $notificationType != 2 && $notificationType != 1) {
                Log::info("google_pay_other",["notificationType" => $notificationType,"order_no" => $orderId,"google_order_id" => $lastOrderId]);
                return $this->buildReturn(Code::ERROR);
            }
            //先查询订单id是否存在与数据库
            $orderId = $result->externalAccountIdentifiers['obfuscatedExternalProfileId'];
            $orderInfo = $this->dataPay->getOrder($orderId);
            if (!$orderInfo) {
                return $this->buildReturn(Code::ERROR);
            }

            $offerId = $result['lineItems'][0]->offerDetails['offerId'];
            $productId = $result['lineItems'][0]->productId;

            DB::beginTransaction();
            try {

                $isSubNotify = false;
                $isPayNotify = false;
                $addUserVip = true;
                $isCopyOrder = false;
                $isTry = false;

                //订阅
                if ($notificationType == 4) {
                    if ($productId == "weekly_pro") {
                        //周订阅试用
                        if ($offerId == "free-weekly-3") {
                            // 试用的已打标记的，就不处理了
                            if ($orderInfo["status"] == 0 && $orderInfo["is_try"] == 1) {
                                return $this->buildReturn(Code::SUCCESS);
                            }
                            if (version_compare($orderInfo['version'],  "1.5.0") >= 0) {
                                //$addUserVip = false;
                                $orderInfo['len'] = 3;

                                $insertData['exper_time'] = $orderInfo['len']*24*3600 + time();
                                $insertData['exper_product'] = $result['lineItems'][0]->offerDetails['basePlanId'];
                                $insertData['user_id'] = $orderInfo['user_id'];
                                $insertData['created_at'] = time();
                                $insertData['device_id'] = $orderInfo['device_id'];
                                $this->dataUserOntrial->createData($insertData);
                            }
                            //订阅
                            $isSubNotify = true;
                            //适用订单打个标记
                            $isTry = true;
                        } else {
                            // 订阅已成功的就不处理了
                            if ($orderInfo["status"] == 1) {
                                return $this->buildReturn(Code::SUCCESS);
                            }
                            //订阅
                            //支付
                            //更新订单号
                            $isSubNotify = true;
                            $isPayNotify = true;
                            $this->dataPay->newUpdatePay($orderInfo['id'],[
                                'external_order_id'=> $lastOrderId,
                                'label' => "2",
                                "region" => $regionCode,
                            ]);
                        }
                    } else {
                        // 订阅已成功的就不处理了
                        if ($orderInfo["status"] == 1) {
                            return $this->buildReturn(Code::SUCCESS);
                        }
                        //订阅
                        //支付
                        //更新订单号
                        $isSubNotify = true;
                        $isPayNotify = true;
                        $this->dataPay->newUpdatePay($orderInfo['id'],[
                            'external_order_id'=> $lastOrderId,
                            'label' => "3",
                            "region" => $regionCode,
                        ]);
                    }
                }

                //扣费
                if ($notificationType == 2 || $notificationType == 1) {
                    //外部订单号已存在，就不处理了
                    $tmpOrderInfo = $this->dataPay->getOrderWithExternalOrderId($lastOrderId);
                    if ($tmpOrderInfo) {
                        return $this->buildReturn(Code::SUCCESS);
                    }
                    if ($productId == "weekly_pro") {
                        if ($offerId == "free-weekly-3") {
                            $lastOrderIdArr = explode("..",$lastOrderId);
                            // 订单号GPA.3312-5684-2244-21394..0，试用过期后的第一笔扣款
                            if (count($lastOrderIdArr) > 1 && $lastOrderIdArr[1] == 0) {
                                //更新订单
                                //支付通知
                                $this->dataPay->newUpdatePay($orderInfo['id'],[
                                    'external_order_id'=> $lastOrderId,
                                    'label' => "1",
                                    "region" => $regionCode,
                                ]);
                            } else {
                                //复制新订单
                                //支付通知
                                $isCopyOrder = true;
                            }
                        } else {
                            //复制新订单
                            //支付通知
                            $isCopyOrder = true;
                        }
                    } else {
                        //复制新订单
                        //支付通知
                        $isCopyOrder = true;
                    }
                    $isPayNotify = true;
                }

                if ($isTry) {
                    $this->dataPay->updatePayById($orderInfo['id'],[
                        "is_try" => 1,
                    ]);
                }

                if ($isCopyOrder) {
                    $insertOrderId = $this->dataPay->makeOrderId();

                    //pauRuleInfo
                    // 实时的取当前支付条款的数据
                    $payRuleInfo = $this->dataPay->getRule($orderInfo["rule_id"]);
                    if (!empty($payRuleInfo)) {
                        $orderInfo["dot"] = $payRuleInfo["dot"];
                        $orderInfo["len"] = $payRuleInfo["len"];
                        $orderInfo["ecy_len"] = $payRuleInfo["ecy_len"];
                    }

                    unset($orderInfo['id']);
                    $orderInfo['parent_order_id'] = $orderInfo['order_id'];
                    $orderInfo['order_id'] = $insertOrderId;
                    $orderInfo['status'] = 1;
                    $orderInfo['external_order_id'] = $lastOrderId;
                    $orderInfo['pay_at'] = FunTool::getReduceTime(4);
                    $orderInfo["label"] = "4";
                    $orderInfo["region"] = $regionCode;

                    $this->dataPay->createOrder($orderInfo);
                }

                //体检vip权益
                if ($addUserVip) {
                    if (version_compare($orderInfo['version'],  "1.4.0") >= 0) {
                        //兼容无登录付费
                        if ($orderInfo["user_id"] > 0 ) {
                            $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
                        }
                    } else {
                        if($orderInfo['len'] > 0 && $orderInfo['ecy_len'] > 0) {
                            $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len']*24*3600, 'vip_exp');
                            $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['ecy_len']*24*3600, 'rcy_vip_exp');
                        }
                    }

                    //兼容无登录付费
                    if($orderInfo['dot'] > 0 && $orderInfo["user_id"] > 0) {
                        $this->dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
                    }
                    //兼容无登录付费
                    if ($orderInfo['len'] > 0 && $orderInfo['ecy_len'] > 0 && $orderInfo['dot'] > 0 && $orderInfo["user_id"] > 0) {
                        //设置充值赠送点数动画值
                        $this->dataUser->setDhNum($orderInfo['user_id'], $orderInfo['dot']);
                    }
                }

                DB::commit();
            } catch (\Exception $e) {
                Log::error("google_pay_error",["error" => $e->getMessage(),"line" => $e->getLine()]);
                DB::rollBack();
                return response("error",Response::HTTP_INTERNAL_SERVER_ERROR);
            }

            /*上报订阅数据到AF 开始*/
            $guid = $orderInfo['device_id'];
            if (empty($guid)) {
                return $this->buildReturn(Code::SUCCESS);
            }
            $systemData = new System();
            $deviceInfo = $systemData->getDevice($guid);
            //$appid = $orderInfo['platform'] == 1 ? "" : "com.jxfq.dalle";
            $appid = FunTool::getAfAppidByPf($orderInfo['platform']);
            $af = new Af();

            if ($isSubNotify) {
				$_aExt = ['line'=>__LINE__, 'in' => 'isPayNotify', 'order' => $orderInfo, 'google_data' => $data];
                $af->subscribeEvent($deviceInfo['appsfly_id'],$appid,$_aExt);
                EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_suc");
            }

            if ($isPayNotify) {
				$_aExt = ['line'=>__LINE__, 'in' => 'isPayNotify', 'order' => $orderInfo, 'google_data' => $data];
				$af->payEvent($deviceInfo['appsfly_id'], $appid, $orderInfo["price"], $_aExt);
                EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_renew");
            }
            /*上报订阅数据到AF 结束*/

        }



    }

    /**
     * @desc 苹果首次订阅商品绑定用户
     */
    public function appleSubscribeBind(Request $request)
    {
        $userId = $this->getTokenUser();
        if (!$userId && !$this->checkNoLoginPay()) {
            return $this->buildReturn(Code::NOT_LOGIN);
        }

        $orderId = $request->post('order_id');
        $receipt = $request->post('receipt');

		$oTester = new Tester();
		$bSandbox = $oTester->isTester($this->getDeviceId());

		//@todo >= 1.8.0 直接走沙盒
		$sVersion = $this->getVersion();
		//if(version_compare($sVersion, '1.8.0') >= 0) {
		//	$bSandbox = true;
		//}

        $orderInfo = DB::table('pay_order')->where('order_id',$orderId)->first();
        if (!empty($orderInfo)) {
            DB::table('pay_order')->where('id',$orderInfo->id)->update(['extend'=>json_encode(['order_id'=>$orderId,'receipt'=>$receipt])]);
        }

		$appleIAP = new AppleInAppPurchaseVerification($receipt, '46c5cf1c64084e5c81f3fe9d17a4be17', $bSandbox);
        $result = $appleIAP->validateReceipt();
        if (!$result) {
            return $this->buildReturn(Code::ERROR);
        }

        $result = json_decode($result, true);
        Log::info("appleSubscribeBind",["appleSubscribeBind" => $result]);

        if (!isset($result['latest_receipt_info'])) {
            return $this->buildReturn(Code::ERROR);
        }
        $latestReceiptList = $result["latest_receipt_info"];
        array_multisort(array_column($latestReceiptList, 'purchase_date_ms'), SORT_DESC, $latestReceiptList);
        $last = $latestReceiptList[0];
        Log::info("lastReceipt",["lastReceipt" => $last]);
        //本次交易流水号
        $transaction_id = $last["transaction_id"];
        //原始订单号
        $original_transaction_id = $last["original_transaction_id"];
        $num = $this->dataPay->getNumByAppleTrade([
            "external_order_id" => $transaction_id,
            "transaction_order_id" => $original_transaction_id,
        ]);
        if ($num > 0) {
            //防止重复订阅
            return $this->buildReturn(Code::ERROR);
        }
        $this->appleSubscribe = true;
        $this->appleSunscribeProduct = $last["product_id"];
        $this->doPay($orderId,$transaction_id,$original_transaction_id);

        return $this->buildReturn(Code::SUCCESS, []);
    }

    /**
     * 苹果订阅通知接口
     */
    public function appleNotifyNew()
    {
        $result = file_get_contents('php://input');

        $result = json_decode($result, true);
        Log::info("appleNotifyNew", ['苹果通知数据：' => $result]);

        if (!isset($result['unified_receipt']['latest_receipt_info'])) {
            return $this->buildReturn(Code::ERROR);
        }

        if ($result['notification_type'] != "DID_RENEW" && $result['notification_type'] != "DID_RECOVER" && $result['notification_type'] != "INTERACTIVE_RENEWAL") {
            return $this->buildReturn(Code::ERROR);
        }

        $latestReceiptList = $result['unified_receipt']['latest_receipt_info'];
        array_multisort(array_column($latestReceiptList, 'purchase_date_ms'), SORT_DESC, $latestReceiptList);
        $last = $latestReceiptList[0];
        Log::info("appleNotifyNew", ['last' => $last]);
        if ($last['transaction_id'] != $last['original_transaction_id']) {
            $good_id = FunTool::getAppleGoodId($last["product_id"]);
            //查询首次订阅的订单
            $orderInfo = $this->dataPay->getOrderTransactionOrderIdByApple($last['original_transaction_id'],$good_id);
            if (!$orderInfo) {
                return $this->buildReturn(Code::SUCCESS);
            }

            //是否重复订阅，当前交易流水号
            $orderInfo2 = $this->dataPay->getOrderWithExternalOrderId($last['transaction_id']);
            if ($orderInfo2) {
                return $this->buildReturn(Code::SUCCESS);
            }

            //pauRuleInfo
            // 实时的取当前支付条款的数据
            $payRuleInfo = $this->dataPay->getRule($orderInfo["rule_id"]);
            if (!empty($payRuleInfo)) {
                $orderInfo["dot"] = $payRuleInfo["dot"];
                $orderInfo["len"] = $payRuleInfo["len"];
                $orderInfo["ecy_len"] = $payRuleInfo["ecy_len"];
            }

            $insertOrderId = $this->dataPay->makeOrderId();
            unset($orderInfo['id']);
            $orderInfo['parent_order_id'] = $orderInfo['order_id'];
            $orderInfo["external_order_id"] = $last['transaction_id'];
            $orderInfo['order_id'] = $insertOrderId;
            $orderInfo['status'] = 1;
            $orderInfo['transaction_order_id'] = $last['original_transaction_id'];
            $orderInfo['pay_at'] = FunTool::getReduceTime(4);
            if (!empty($orderInfo['parent_order_id'])) {
                $orderInfo['label'] = 4;
            }
            $this->dataPay->createOrder($orderInfo);

            /*上报订阅数据到AF 开始*/
            if ($orderInfo["device_id"]) {
                $systemData = new System();
                $deviceInfo = $systemData->getDevice($orderInfo["device_id"]);
                $appid = FunTool::getAfAppidByPf(1);
                if ($deviceInfo["appsfly_id"]) {
					$_aExt = ['line' => __LINE__, 'in' => 'appleNotifyNew', 'order' => $orderInfo, 'app_result' => $result];
					(new Af())->payEvent($deviceInfo["appsfly_id"], $appid, $orderInfo['price'], $_aExt);
                    EventList::getInstance()->subscribePayEvent($orderInfo["platform"],$orderInfo["version"],$orderInfo["device_id"],"subscribe_renew");
                }
            }

            //兼容无登录付费
            if($orderInfo['len'] > 0 && $orderInfo['len'] != 36500 && $orderInfo['user_id'] > 0) {
                if ($orderInfo['is_gold'] == 1) {
                    //续费黄金会员的时间
                    $this->dataUser->updateVipExp($orderInfo['user_id'], $orderInfo['len'] * 24 * 3600, 'vip_exp');
                } else {
                    $userDrawing = new UserDrawing();
                    //续费普通画板的时间
                    $userDrawing->updateUserDrawExp($orderInfo['user_id'], $orderInfo['drawing_id'], $orderInfo['len'] * 24 * 3600);
                }
            }

            //兼容无登录付费
            if($orderInfo['dot'] > 0 && $orderInfo['user_id'] > 0) {
                $this->dataUser->updateDot($orderInfo['user_id'], $orderInfo['dot'], 4);
            }
        }

        return $this->buildReturn(Code::SUCCESS);
    }


    /**
     * 客户端谷歌支付成功后同步结果透传给服务端
     */
    public function googleClientNotify(Request $request){

        $this->validate($request, [
            'order_id' => ['required'],
            'type' => ['required']
        ]);
      
        $orderId = $request->post('order_id');
        $data = $request->post('data');
        $type = $request->post('type');//类型：1成功，2失败

        Log::info("googleClientNotify-".$orderId, ['data'=>$data,'type'=>$type,'order_id'=>$orderId]);

        $rowData = [];
        $updateData = [];
        $updateData['client_notify'] = $type; 
        if ($type == 1) {//成功
            $this->validate($request, [
                'data' => ['required'],
            ]);
            $rowData = empty($data) ? [] : json_decode($data, true);

            $rowData['type'] = 1;
            $rowData['order_id'] = $orderId;

            Log::info("googleClientNotify-".$orderId, $rowData);

            $order_id = $orderId;
            if ($type == 1 && isset($rowData['obfuscatedProfileId'])) {
                $order_id = $rowData['obfuscatedProfileId'];
            }
            $orderInfo = $this->dataPay->getFirstInfo(['order_id'=>$order_id]);
            $updateData['extend'] =  json_encode($rowData);

        }else{//失败
            $order_id = $orderId;
            if ($type == 1 && isset($rowData['obfuscatedProfileId'])) {
                $order_id = $rowData['obfuscatedProfileId'];
            }
            $orderInfo = $this->dataPay->getFirstInfo(['order_id'=>$order_id]);
        }

        $this->dataPay->updatePayById($orderInfo['id'], $updateData);

        return $this->buildReturn(Code::SUCCESS);

    }


    public function googleOrderInfo(Request $request)
    {
        $orderId = $request->post('order_id');
        $productId = $request->post('product_id');
        $token = $request->post('token');
        $orderInfo = $this->dataPay->getFirstInfo(['order_id'=>$orderId]);
        if (empty($orderInfo)) {
            return $this->buildReturn(Code::ERROR, ['订单不存在']);
        }
        try{
            if (1 == $orderInfo['google_is_subscribe']) {//订阅的

                $result = GooglePay::getGoogleSubscribeOrderInfo($orderId, $token);

            }else{//购买产品的
                  $result = GooglePay::getGooglePurchaseOrderInfo($orderId, $productId, $token);
            }
            return $this->buildReturn(Code::SUCCESS, $result);
        }catch(\Exception $e){
            return $this->buildReturn(Code::ERROR, [$e->getMessage()]);
        }
    }

    public function appleOrderInfo(Request $request){
        
        $orderId = $request->post('order_id');
        $orderInfo = DB::table('pay_order')->where('order_id',$orderId)->first();
        $extend = json_decode($orderInfo->extend, true);
        $receipt = $extend['receipt'] ?? '';
        $appleIAP = new AppleInAppPurchaseVerification($receipt, '46c5cf1c64084e5c81f3fe9d17a4be17', true);
        $result = $appleIAP->validateReceipt();
        $result = json_decode($result, true);
        Log::info("apple_order_info-".$orderId,["result" => $result]);

        return $result;

    }


    public function getTest88()
    {
        $appid = "com.jxfq.dalle";
        $orderInfo['google_id'] = "ceshi";
        $af = new Af();
        $af->reportEvent("1680781747679-1126496250108172397" , $appid, ['eventName' => "subscribe", "eventValue" => $orderInfo['google_id']]);

    }




}
